<template>
  <div class="plan-select-node">
    <div class="node-header">
      <h3 class="node-title">预案选择</h3>
      <div class="button-group">
        <el-button type="primary" @click="handleSavePlan" :disabled="!matchForm.selectedPlan || isCompleted">
          保存
        </el-button>
        <el-button type="success" @click="handleNextStep" :disabled="!matchForm.selectedPlan || isCompleted">
          下一步
        </el-button>
      </div>
    </div>

    <el-form ref="matchFormRef" :model="matchForm" :rules="matchRules" label-width="120px" class="dialog-form">
      <el-form-item label="预案类型" prop="planType">
        <el-radio-group v-model="matchForm.planType" @change="handlePlanTypeChange" :disabled="isCompleted">
          <el-radio :label="1">总体预案</el-radio>
          <el-radio :label="2">专项预案</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择预案" prop="planId">
        <el-select v-model="matchForm.planId" placeholder="请选择预案" class="w-full" @change="handlePlanChange" filterable :disabled="isCompleted">
          <el-option v-for="plan in filteredPlanList" :key="plan.id" :label="plan.planName" :value="plan.id" />
        </el-select>
      </el-form-item>

      <!-- 预案详情展示区域 -->
      <template v-if="matchForm.selectedPlan">
        <div class="plan-details-card">
          <div class="card-header">
            <div class="card-title">预案详情</div>
            <el-tag size="small" :type="matchForm.selectedPlan.planType === 1 ? 'primary' : 'warning'">
              {{ matchForm.selectedPlan.planType === 1 ? '总体预案' : '专项预案' }}
            </el-tag>
          </div>
          <div class="card-content">
            <el-descriptions border :column="2">
              <el-descriptions-item label="预案名称" :span="2">
                {{ matchForm.selectedPlan.planName }}
              </el-descriptions-item>
              <el-descriptions-item label="适用事件类型">
                <el-tag :type="getEventCategoryTag(matchForm.selectedPlan.eventCategory)">
                  {{ getEventCategoryName(matchForm.selectedPlan.eventCategory) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="适用事件等级">
                <el-tag :type="getEventLevelTag(matchForm.selectedPlan.eventLevel)">
                  {{ getEventLevelName(matchForm.selectedPlan.eventLevel) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="发布单位" :span="2">
                {{ matchForm.selectedPlan.publishUnit }}
              </el-descriptions-item>
              <el-descriptions-item label="发布时间" :span="2">
                {{ formatDateTime(matchForm.selectedPlan.publishTime) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </template>
    </el-form>
    
    <div class="tip-section" v-if="matchForm.selectedPlan">
      <el-alert
        title="预案选择完成后，点击'保存'将预案信息保存到事件中，或点击'下一步'进入险情同步环节"
        type="success"
        :closable="false"
        show-icon
      />
    </div>
    <div class="tip-section" v-else>
      <el-alert
        title="请先选择一个应急预案"
        type="info"
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, defineProps, defineEmits } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { getEmergencyPlanList, getEmergencyPlanById } from '@/api/bridge/command/emergency';
import { updateEmergencyEvent } from '@/api/bridge/command/event';

const props = defineProps({
  eventData: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['next-step']);

// 匹配表单相关
const matchFormRef = ref();
const matchForm = ref({
  planType: 1,
  planId: null,
  selectedPlan: null
});

// 表单校验规则
const matchRules = {
  planType: [{ required: true, message: '请选择预案类型', trigger: 'change' }],
  planId: [{ required: true, message: '请选择预案', trigger: 'change' }]
};

const emergencyPlanList = ref([]);

// 计算筛选后的预案列表
const filteredPlanList = computed(() => {
  return emergencyPlanList.value.filter(plan => plan.planType === matchForm.value.planType);
});

// 获取应急预案列表方法
const loadEmergencyPlanList = async () => {
  try {
    const res = await getEmergencyPlanList({
      pageNum: 1,
      pageSize: 1000000
    });
    if (res.code === 200) {
      emergencyPlanList.value = res.rows;
    }
  } catch (error) {
    console.error("获取应急预案列表失败:", error);
  }
};

// 处理预案类型变化
const handlePlanTypeChange = () => {
  // 重置表单
  matchForm.value = {
    planType: matchForm.value.planType,
    planId: null,
    selectedPlan: null
  };
};

// 处理预案变化
const handlePlanChange = async (planId) => {
  try {
    if (!planId) {
      matchForm.value.selectedPlan = null;
      return;
    }

    // 先从当前列表中查找预案
    const plan = emergencyPlanList.value.find(p => p.id === planId);
    if (plan) {
      matchForm.value.selectedPlan = { ...plan };
    } else {
      // 如果在列表中找不到，则通过API获取
      const res = await getEmergencyPlanById(planId);
      if (res.code === 200) {
        matchForm.value.selectedPlan = res.data;
      } else {
        ElMessage.error("获取预案详情失败");
        return;
      }
    }
  } catch (error) {
    console.error("处理预案变化失败:", error);
    ElMessage.error("获取预案详情失败");
  }
};

// 保存预案信息到事件
const handleSavePlan = async () => {
  if (!matchFormRef.value) return;
  await matchFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!matchForm.value.selectedPlan) {
        ElMessage.warning('请先选择一个预案');
        return;
      }

      try {
        // 更新事件的planId字段
        const updateData = {
          ...props.eventData,
          planId: matchForm.value.planId
        };
        const res = await updateEmergencyEvent(updateData);
        
        if (res.code === 200) {
          ElMessage.success('预案信息已保存');
          
          // 存储选中的预案信息，以便下一步使用
          localStorage.setItem('selectedPlan', JSON.stringify(matchForm.value.selectedPlan));
          
          // 询问是否进入险情同步阶段
          ElMessageBox.confirm(
            '预案信息已保存，是否进入险情同步阶段？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'info'
            }
          ).then(() => {
            handleNextStep();
          }).catch(() => {
            // 用户选择取消操作
          });
        } else {
          ElMessage.error(res.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存预案信息失败:', error);
        ElMessage.error('保存失败');
      }
    }
  });
};

// 进入下一步
const handleNextStep = async () => {
  if (!matchFormRef.value) return;
  
  await matchFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!matchForm.value.selectedPlan) {
        ElMessage.warning('请先选择一个预案');
        return;
      }

      try {
        // 仅更新planId，而不更新flowStatus
        // 避免与flowLog.vue中的goToNextNode重复调用更新接口
        const updateData = {
          ...props.eventData,
          planId: matchForm.value.planId
        };
        
        const res = await updateEmergencyEvent(updateData);
        
        if (res.code === 200) {
          // 存储选中的预案信息，以便下一步使用
          localStorage.setItem('selectedPlan', JSON.stringify(matchForm.value.selectedPlan));
          
          ElMessage.success('进入险情同步阶段');
          emit('next-step');
        } else {
          ElMessage.error(res.msg || '操作失败');
        }
      } catch (error) {
        console.error('进入下一步失败:', error);
        ElMessage.error('操作失败');
      }
    }
  });
};

// 获取事件类型名称
const getEventCategoryName = (category) => {
  const categories = {
    1: '自然灾害',
    2: '事故灾难',
    3: '公共卫生事件',
    4: '社会安全事件',
    5: '全部'
  };
  return categories[category] || '未知';
};

// 获取事件类型标签样式
const getEventCategoryTag = (category) => {
  const tags = {
    1: 'danger',
    2: 'warning',
    3: 'success',
    4: 'info',
    5: 'primary'
  };
  return tags[category] || '';
};

// 获取事件等级名称
const getEventLevelName = (level) => {
  const levels = {
    1: 'Ⅰ级',
    2: 'Ⅱ级',
    3: 'Ⅲ级',
    4: 'Ⅳ级',
    5: '全部'
  };
  return levels[level] || '未知';
};

// 获取事件等级标签样式
const getEventLevelTag = (level) => {
  const tags = {
    1: 'danger',
    2: 'warning',
    3: 'success',
    4: 'info',
    5: 'primary'
  };
  return tags[level] || '';
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

const isCompleted = computed(() => {
  return props.eventData && props.eventData.flowStatus === 7;
});

onMounted(async () => {
  await loadEmergencyPlanList();
  
  // 如果事件已有planId，则自动选择对应的预案
  if (props.eventData && props.eventData.planId) {
    matchForm.value.planId = props.eventData.planId;
    await handlePlanChange(props.eventData.planId);
  }
});
</script>

<style scoped lang="scss">
.plan-select-node {
  padding: 20px;
  
  .node-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .node-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: var(--el-text-color-primary);
    }
    
    .button-group {
      display: flex;
      gap: 10px;
    }
  }
  
  .tip-section {
    margin-top: 20px;
  }
  
  .w-full {
    width: 100%;
  }
  
  .plan-details-card {
    margin: 20px 0;
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    overflow: hidden;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      background-color: var(--el-fill-color-light);
      border-bottom: 1px solid var(--el-border-color-light);
      
      .card-title {
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }
    
    .card-content {
      padding: 16px;
    }
  }
  
  // 描述列表样式优化
  :deep(.el-descriptions) {
    .el-descriptions__label {
      width: 120px;
      color: var(--el-text-color-secondary);
    }
    
    .el-descriptions__content {
      color: var(--el-text-color-primary);
    }
  }
}
</style> 